//
//  NSString+MAAdv.m
//  MateAdv
//
//  Created by 茶 on 2023/9/8.
//

#import "NSString+MAAdv.h"
#import "NSData+MAAdv.h"

#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

@implementation NSString (MAAdv)

- (NSString *)AES128DecryptWithkey:(NSString *)key iv:(NSString *)iv{
    return [[NSString alloc] initWithData:[self.hexData stds_aes256DecryptWithkey:[key dataUsingEncoding:NSUTF8StringEncoding] iv:[iv dataUsingEncoding:NSUTF8StringEncoding]] encoding:NSUTF8StringEncoding];
}

- (NSString *)AES128EncryptWithKey:(NSString *)key iv:(NSString *)iv {
    return [[self dataUsingEncoding:NSUTF8StringEncoding] stds_aes256EncryptWithKey:[key dataUsingEncoding:NSUTF8StringEncoding] iv:[iv dataUsingEncoding:NSUTF8StringEncoding]].hexString;
}

- (NSData *)dataValue {
    return [self dataUsingEncoding:NSUTF8StringEncoding];
}

- (id)jsonValue {
    return [[self dataValue] jsonValue];
}

- (NSData *)hexData{
    if ([self length] ==0) {
        return nil;
    }
    NSMutableData *hexData = [[NSMutableData alloc]initWithCapacity:[self length]*2];
    NSRange range;
    if ([self length] %2==0) {
        range = NSMakeRange(0,2);
    } else {
        range = NSMakeRange(0,1);
    }
    for (NSInteger i = range.location; i < [self length]; i +=2) {
        unsigned int anInt;
        NSString *hexCharStr = [self substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc]initWithString:hexCharStr];
        
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc]initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        
        range.location+= range.length;
        range.length=2;
    }
    return hexData;
}
@end
